import os
import datetime
import signal
import sys
import subprocess
import time

# 全局变量用于控制循环
running = True

# 设置录音文件存储目录
RECORDINGS_DIR = "recordings"

def signal_handler(sig, frame):
    """处理中断信号"""
    global running
    print("\n正在停止录音...")
    running = False

def ensure_recordings_dir():
    """确保录音目录存在"""
    if not os.path.exists(RECORDINGS_DIR):
        os.makedirs(RECORDINGS_DIR)
        print(f"创建录音目录: {RECORDINGS_DIR}")
    return RECORDINGS_DIR

def recs():
    """录音主函数"""
    global running
    
    # 确保录音目录存在
    recordings_dir = ensure_recordings_dir()
    
    # 设置信号处理
    signal.signal(signal.SIGINT, signal_handler)  # Ctrl+C
    signal.signal(signal.SIGTERM, signal_handler)  # 终止信号
    
    i = 1
    print("开始录音，按 Ctrl+C 停止...")
    print(f"录音文件将保存在: {os.path.abspath(recordings_dir)}")
    
    while running:
        try:
            print(f'录音片段: {i}')
            tim = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
            filename = f'f{tim}.wav'
            filepath = os.path.join(recordings_dir, filename)
            
            # 使用sox录音
            cmd = f'sox -t alsa plughw:1 {filepath} trim 0 00:00:60'
            
            print(f"正在录制: {filename}")
            
            # 使用subprocess运行，可以更好地控制进程
            process = subprocess.Popen(cmd, shell=True)
            
            # 等待进程完成或检测到停止信号
            while process.poll() is None and running:
                time.sleep(0.1)  # 短暂睡眠以减少CPU使用
                
            # 如果用户要求停止，终止sox进程
            if not running and process.poll() is None:
                process.terminate()
                # 给进程一点时间正常退出
                time.sleep(0.5)
                # 如果仍然在运行，强制终止
                if process.poll() is None:
                    process.kill()
                print("录音已终止")
                break
            
            # 检查文件是否成功创建
            if os.path.exists(filepath):
                file_size = os.path.getsize(filepath)
                print(f"录音完成: {filename} ({file_size} bytes)")
            else:
                print(f"警告: 文件未创建: {filename}")
                
            i += 1
            
        except KeyboardInterrupt:
            print("\n用户中断")
            running = False
        except Exception as e:
            print(f"发生错误: {e}")
            running = False
    
    print("程序已安全退出")

if __name__ == "__main__":
    recs()
